<?php

/**
 * tallyin actions.
 *
 * @package    student_manager
 * @subpackage tallyin
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2288 2006-10-02 15:22:13Z fabien $
 */
class tallyinActions extends autotallyinActions
{
public function executeRevise(){
     $this->getResponse()->setTitle('EXECUTERIVISE');
    $Id = $this->getRequestParameter('id');
    $obj = TallyInPeer::retrieveByPK($Id);
    if (!$obj){
        $this->getRequest()->setError('revise', 'This TI is not available!');
        $this->forward('TallyIn', 'list');
    }
    if ($obj->getStatus()!= 1 ) {
        $this->getRequest()->setError('revise', 'Could not revise this TI!');
        $this->forward('TallyIn', 'list');
    }
    $this->redirect('TallyIn/edit?prepare_revise_Id='.$Id);
}

	
public function executeChangeNumber(){
     $this->getResponse()->setTitle('WMS-Change-No-TallyIn');
	$id = $this->getRequestParameter('id');
    if ($this->getRequest()->isMethod('post')){    	
    	$no = $this->getRequestParameter('no');
    	if ($id && $no){
    		$obj = TallyInPeer::retrieveByPK($id);
    		if ($obj){
	    		$obj->setTallyincode($no);
	    		$obj->save();
	    		$this->getUser()->setFlash('notice',  'change TallyIn number successfully!');
	    		return $this->redirect("TallyIn/list?id=$id");
    		}
    	}
    }
    
    $obj = TallyInPeer::retrieveByPK($id);
    $this->no = $obj->getTallyincode();
    $this->id = $id;
}
//
public function executeChangeDate()
{
    if (!$this->getUser()->hasCredential('EDIT_TALLYIN'))
    {
        $this->getUser()->setFlash('notice',  'You dont have permission to edit TallyIn!');
        return $this->redirect("TallyIn/list?id=$id");
    }
     
    $id = $this->getRequestParameter('id');
    
    $obj = TallyInPeer::retrieveByPK($id);
    if (!$obj)
    {
        $this->getUser()->setFlash('notice',  'TallyIn is not exist!');
        return $this->redirect("TallyIn/list");
    }
    if ($obj->getStatus() != CommonValues::$gTLStatus['key']['Published'])
    {
        $this->getUser()->setFlash('notice',  'This TallyIn is not yet published!');
        return $this->redirect("TallyIn/list?id=$id");
    }
    
    $this->getResponse()->setTitle('WMS-TallyIn-Change-Date-'.$obj->getTallyincode());
     //Lay ve Id cua Tally In
  
    if ($this->getRequest()->isMethod('post'))
    {    
        //Lay ve ngay can thay doi
    	$date = $this->getRequestParameter('changedate'); 
        
    	if ($date)
        {           
            $obj->setCreatedAt($date);
            $obj->save();
            
            //kiem tra neu TI cho PO va PO ton tai thi cap nhat lai ngay nhan hang tre nhat cho PO
            if ($obj->getType()==CommonValues::$gTallyInType['key']['Supplier'])                   
            {
                $po = POPeer::retrieveByPK($obj->getTallyno()); 
                if (!$po) 
                {
                    $this->getUser()->setFlash('notice',  'This TallyIn of Supplier but there is no PO!');
                    return $this->redirect("TallyIn/list?id=$id");
                }
                
               if (!$po->getReceiveddate() || $po->getReceiveddate() < $date)
                {                                   
                    $po->setReceiveddate($date);
                    $po->save();                                  
                    $this->getUser()->setFlash('notice',  'Change date of TI-'.$obj->getTallyincode().' and update PO received date successfully!');
                    return $this->redirect("TallyIn/list?id=$id");
                }  
            }      
            $this->getUser()->setFlash('notice',  'Change date of TI-'.$obj->getTallyincode().' successfully!');
            return $this->redirect("TallyIn/list?id=$id");
        }
    }
    $this->changedate = $obj->getCreatedAt();     
    $this->id = $id;
}

public function executePrint(){
    $this->getResponse()->setTitle('PRINT-TALLYIN');
    $id = $this->getRequestParameter('id');
    $this->tallyin = TallyInPeer::retrieveByPK($id);
    //$this->tallyin = new TallyIn();
    if (!$this->tallyin) {
        $this->getRequest()->setError('print', 'This TallyIn is not available.');        
        $this->forward('tallyin', 'list');
    }
    if ($this->tallyin->getType() == CommonValues::$gTallyInType['key']['Supplier']){
        $this->po = POPeer::retrieveByPK($this->tallyin->getTallyno());
        if (!$this->po) {
            $this->getRequest()->setError('print', 'PO of this TallyIn is not available.');        
            $this->forward('tallyin', 'list');
        }
    }
    
    if ($this->tallyin->getType() == CommonValues::$gTallyInType['key']['Production']){
        $bom = BOMPeer::retrieveByPK($this->tallyin->getTallyno());
        if (!$bom) {
            $this->getRequest()->setError('print', 'Project of this TallyIn is not available.');        
            $this->forward('tallyin', 'list');
        }
        $this->projectname = $bom->getProject();
    }
    
    if ($this->tallyin->getType() == CommonValues::$gTallyInType['key']['Service']){
        $this->DOno = $this->tallyin->getTallyno();
    }
    $compGroupId = $this->tallyin->getComponentgroupId();
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $compGroupId);
    $this->compsList = ComponentsPeer::doSelect($c);
    if (!$this->compsList || !count($this->compsList)){        
        $this->getRequest()->setError('print', 'There is no component in this TallyIn.');        
        $this->forward('tallyin', 'list');
    }
}
  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['tallyincode_is_empty']))
    {
      $criterion = $c->getNewCriterion(TallyInPeer::TALLYINCODE, '');
      $criterion->addOr($c->getNewCriterion(TallyInPeer::TALLYINCODE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['tallyincode']) && $this->filters['tallyincode'] !== '')
    {
      $c->add(TallyInPeer::TALLYINCODE, '%'.strtr($this->filters['tallyincode'], '*', '%').'%', Criteria::LIKE);
    }
    if (isset($this->filters['type_is_empty']))
    {
      $criterion = $c->getNewCriterion(TallyInPeer::TYPE, '');
      $criterion->addOr($c->getNewCriterion(TallyInPeer::TYPE, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['type']) && $this->filters['type'] !== '')
    {
      $c->add(TallyInPeer::TYPE, $this->filters['type']);
    }
    if (isset($this->filters['tallyno_is_empty']))
    {
      $criterion = $c->getNewCriterion(TallyInPeer::TALLYNO, '');
      $criterion->addOr($c->getNewCriterion(TallyInPeer::TALLYNO, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['tallyno']) && $this->filters['tallyno'] !== '')
    {
        if ($this->filters['type']== CommonValues::$gTallyInType['key']['Supplier'])
        {
            $c->addJoin(TallyInPeer::TALLYNO, POPeer::ID);
            $c->add(POPeer::PONO, '%'.strtr($this->filters['tallyno'], '*', '%').'%', Criteria::LIKE);
        } 
        else if ($this->filters['type']== CommonValues::$gTallyInType['key']['Project'])
        {
            $c->addJoin(TallyInPeer::TALLYNO, BOMPeer::ID);
            $c->add(BOMPeer::WONO, '%'.strtr($this->filters['tallyno'], '*', '%').'%', Criteria::LIKE);
        }
        else if ($this->filters['type']== CommonValues::$gTallyInType['key']['Production'])
        {
            $c->addJoin(TallyInPeer::TALLYNO, ProjectPeer::ID);
            $c->add(ProjectPeer::SALENO, '%'.strtr($this->filters['tallyno'], '*', '%').'%', Criteria::LIKE);
        }
        else
            $c->add(TallyInPeer::TALLYNO, '%'.strtr($this->filters['tallyno'], '*', '%').'%', Criteria::LIKE);
    }


    if (isset($this->filters['status_is_empty']))
    {
      $criterion = $c->getNewCriterion(TallyInPeer::STATUS, '');
      $criterion->addOr($c->getNewCriterion(TallyInPeer::STATUS, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['status']) && $this->filters['status'] !== '')
    {
      $c->add(TallyInPeer::STATUS, $this->filters['status']);
    }

    
    if (isset($this->filters['created_at_is_empty']))
    {
      $criterion = $c->getNewCriterion(TallyInPeer::CREATED_AT, '');
      $criterion->addOr($c->getNewCriterion(TallyInPeer::CREATED_AT, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['created_at']))
    {
      if (isset($this->filters['created_at']['from']) && $this->filters['created_at']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(TallyInPeer::CREATED_AT, $this->filters['created_at']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['created_at']['to']) && $this->filters['created_at']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(TallyInPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(TallyInPeer::CREATED_AT, $this->filters['created_at']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
  }

  public function executeDelete()
  {
       $this->getResponse()->setTitle('DELETE-TALLYIN');
    $this->tally_in = TallyInPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->tally_in);
    
    if ($this->tally_in->getStatus()==1
            && !$this->getUser()->hasGroup('Administrator') ){
        $this->getRequest()->setError('delete', 'Could not delete the selected Tally in. It was published.');
        return $this->forward('tallyin', 'list');
    }

    if ($this->tally_in->getStatus()==1 && $this->tally_in->getType() == CommonValues::$gTallyInType['key']['Supplier'])
    {
        $po = POPeer::retrieveByPK($this->tally_in->getTallyno());
        if ($po){
            $POCompGroupId = $po->getComponentgroupId();
            $comgroupid = $this->tally_in->getComponentgroupId();
            $c = new Criteria();
            $c->add(ComponentsPeer::COMPONENTGROUP_ID, $comgroupid);
            $compsList = ComponentsPeer::doSelect($c);
            foreach ($compsList as $comps){
                $c = new Criteria();
                $c->add(WarehousePeer::COMPONENT_ID , $comps->getComponentId());
                $wh = WarehousePeer::doSelectOne($c);
                if ($wh){
                    $wh->setQtyordered($wh->getQtyordered() + $comps->getQty1());
                    $wh->save();
                }
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENT_ID , $comps->getComponentId());
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POCompGroupId);
                $comps1 = ComponentsPeer::doSelectOne($c);
                if ($comps1)  {
                    $comps1->setQty4($comps1->getQty4() + $comps->getQty1());
                    $comps1->save();
                }
            }
        }
    }


    try
    {
      $this->deleteTallyIn($this->tally_in);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Tally in. Make sure it does not have any associated items.');
      return $this->forward('tallyin', 'list');
    }

    $this->getUser()->setFlash('notice', 'This Tallyin was deleted successfully.');
    return $this->redirect('tallyin/list');
  }

public function executePublish() {
     $this->getResponse()->setTitle('WMS-Publish-TallyIn');
    $Id = $this->getRequestParameter('id');
    
    $tally_in = TallyInPeer::retrieveByPK($Id);
    if (!$tally_in ){
        $this->getRequest()->setError('publish', 'This TallyIn is not available.');        
        $this->forward('tallyin', 'list');
    }
    
    if ($tally_in->getStatus()==1) {
        $this->getRequest()->setError('publish', 'This TallyIn has been published adready.');
        $this->forward('tallyin','list');        
    }
    
    $componentGroupId = $tally_in->getComponentgroupId();
    $c = new Criteria();
    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
    $componentsList = ComponentsPeer::doSelect($c);
    if (!$componentsList || !count($componentsList)){
        $this->getRequest()->setError('publish', 'This TallyIn has not any components.');
        $this->forward('tallyin','list');
    }
    $POGroupId  = null;    
    $BOMGroupId = null;
    
    if ($tally_in->getType() == CommonValues::$gTallyInType['key']['Supplier']) {
        $po = POPeer::retrieveByPK($tally_in->getTallyno());
        $POGroupId = $po? $po->getComponentgroupId(): null;
    } elseif ($tally_in->getType() == CommonValues::$gTallyInType['key']['Project']) {
        $bom = BOMPeer::retrieveByPK($tally_in->getTallyno());
        $BOMGroupId = $bom? $bom->getComponentgroupId() : null;
    }

    //REVISE
    if ($tally_in->getReviseId())
    {
        $rvTI = TallyInPeer::retrieveByPK($tally_in->getReviseId());
        if (!$rvTI){
            echo "Revise TI bi xoa";
            exit();
        }
        $rvGroupId = $rvTI->getComponentgroupId();
        
        foreach ($componentsList as $comps) {
            $componentId = $comps->getComponentId();
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $componentId);
            $warehouse = WarehousePeer::doSelectOne($c);

            $c = new Criteria();
            $c->add(ComponentsPeer::COMPONENTGROUP_ID, $rvGroupId);
            $c->add(ComponentsPeer::COMPONENT_ID, $componentId);
            $rvComps = ComponentsPeer::doSelectOne($c);

            $qty = 0;
            if ($rvComps) $qty = $rvComps->getQty1();

            $warehouse->setTotalin($warehouse->getTotalin() + $comps->getQty1() - $qty);
            $warehouse->setClosing($warehouse->getClosing() + $comps->getQty1() - $qty);

            if ($POGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POGroupId);
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $POcomponents = ComponentsPeer::doSelectOne($c);
                if ($POcomponents){

                    $POcomponents->setQty4($POcomponents->getQty4() - $comps->getQty1() + $qty);
                    $POcomponents->save();

                    //update qty outstanding PO for tally in
                    $comps->setQty4($POcomponents->getQty4());
                    $comps->save();

                    //update warehouse
                    $warehouse->setQtyordered($warehouse->getQtyordered() - $comps->getQty1() + $qty);
                }
            }
            elseif ($BOMGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $BOMGroupId);
                $BOMcomps = ComponentsPeer::doSelectOne($c);
                if ($BOMcomps)
                {
                    $BOMcomps->setQty4($BOMcomps->getQty4() + $comps->getQty1() - $qty);
                    $BOMcomps->save();
                }
            }
            //update warehouse
            $warehouse->save();
        }

        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID, $rvGroupId);
        $rvCompsList = ComponentsPeer::doSelect($c);

        $GroupId = $tally_in->getComponentgroupId();

        foreach ($rvCompsList as $rvComps) {
            $componentId = $rvComps->getComponentId();
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $componentId);
            $warehouse = WarehousePeer::doSelectOne($c);

            $c = new Criteria();
            $c->add(ComponentsPeer::COMPONENTGROUP_ID, $GroupId);
            $c->add(ComponentsPeer::COMPONENT_ID, $componentId);
            $Comps = ComponentsPeer::doSelectOne($c);

            if ($Comps) continue;

            $warehouse->setTotalin($warehouse->getTotalin() - $rvComps->getQty1());
            $warehouse->setClosing($warehouse->getClosing() - $rvComps->getQty1());

            if ($POGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POGroupId);
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $POcomponents = ComponentsPeer::doSelectOne($c);

                if ($POcomponents){

                    $POcomponents->setQty4($POcomponents->getQty4() + $rvComps->getQty1());
                    $POcomponents->save();

                    //update qty outstanding PO for tally in
                    $comps->setQty4($POcomponents->getQty4());
                    $comps->save();

                    //update warehouse
                    $warehouse->setQtyordered($warehouse->getQtyordered() + $rvComps->getQty1());
                }
            }
            elseif ($BOMGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $BOMGroupId);
                $BOMcomps = ComponentsPeer::doSelectOne($c);
                if ($BOMcomps){
                    $BOMcomps->setQty4($BOMcomps->getQty4() - $rvComps->getQty1());
                    $BOMcomps->save();
                }
            }
            //update warehouse
            $warehouse->save();
        }
        
        $rvTI->setStatus(CommonValues::$gTLStatus['key']['Revised']);
    }
    //khong revise
    else {
    
        foreach ($componentsList as $comps) {
            $componentId = $comps->getComponentId();
            $c = new Criteria();
            $c->add(WarehousePeer::COMPONENT_ID , $componentId);
            $warehouse = WarehousePeer::doSelectOne($c);

            $warehouse->setTotalin($warehouse->getTotalin() + $comps->getQty1());
            $warehouse->setClosing($warehouse->getClosing() + $comps->getQty1());

            //tally in cho supplier
            if ($POGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POGroupId);
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $POcomponents = ComponentsPeer::doSelectOne($c);

                if ($POcomponents){
                
                    $POcomponents->setQty4($POcomponents->getQty4() - $comps->getQty1());
                    $POcomponents->save();

                    //update qty outstanding PO for tally in
                    $comps->setQty4($POcomponents->getQty4());
                    $comps->save();
                    //update warehouse
                    $warehouse->setQtyordered($warehouse->getQtyordered() - $comps->getQty1());
                }
            }
            elseif ($BOMGroupId){
                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                $c->add(ComponentsPeer::COMPONENTGROUP_ID , $BOMGroupId);
                $BOMcomps = ComponentsPeer::doSelectOne($c);
                if ($BOMcomps){
                    $BOMcomps->setQty4($BOMcomps->getQty4() + $comps->getQty1());
                    $BOMcomps->save();
                }
            }
            //update warehouse
            $warehouse->save();
        }
    }    
    
    $tally_in->setStatus(CommonValues::$gTLStatus['key']['Published']);
    $tally_in->save();
    
    $this->getUser()->setFlash('notice', 'This TallyIn was published successfully.');
    
    if ($POGroupId){
        $c = new Criteria();
        $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POGroupId);
        $POcomponentsList = ComponentsPeer::doSelect($c);
        $bFullReceived = true;
        foreach ($POcomponentsList as $components) {
            if ($components->getQty4() >0) {
                $bFullReceived = false;
                break;
            }
        }
        //Cap nhat lai ngay nhan hang voi TI date tre nhat
        if ($po && ($po->getReceiveddate() == NULL || $po->getReceiveddate() < $tally_in->getCreateAt()))
            $po->setReceiveddate($tally_in->getCreateAt());
        
        //Thay doi trang thai da nhan du hang
        if ($bFullReceived && $po){
            $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Fully Received']);
            $po->save();
            
            $this->getUser()->setFlash('notice', 'This TallyIn was published successfully and the PO status is fully received.');            
        } elseif ($po){
            $po->setReceivedstatus(CommonValues::$gPOReceivedStatus['key']['Partially Received']);
            $po->save();
            
            $this->getUser()->setFlash('notice', 'This TallyIn was published successfully and the PO status is partially received.');
        }
    }
    
    $this->redirect('tallyin/list?id='.$Id);
}
    public function executeTallyinNoAjax(){
         $this->getResponse()->setTitle('NO-TALLYIN');
        $this->type = $this->getRequestParameter('type');
    }
    public function executeBuildListAjax(){
         $this->getResponse()->setTitle('BUILD_LIST-TALLYIN');
        $this->type = $this->getRequestParameter('type');
        $this->tallyno = $this->getRequestParameter('tallyno');
        if ($this->type ==CommonValues::$gTallyInType['key']['Supplier']) {
            $po = POPeer::retrieveByPK($this->tallyno);
            if ($po) {
                $componentgroupId = $po->getComponentgroupId();
                if ($componentgroupId){
                    $c1 = new Criteria();
                    $c1->add(ComponentsPeer::COMPONENTGROUP_ID , $componentgroupId);
                    $this->compsList = ComponentsPeer::doSelect($c1);
                }
            }
        } elseif ($this->type ==CommonValues::$gTallyInType['key']['Project']) {
            $bom = BOMPeer::retrieveByPK($this->tallyno);
            if ($bom) {
                $componentgroupId = $bom->getComponentgroupId();
                if ($componentgroupId){
                    $c1 = new Criteria();
                    $c1->add(ComponentsPeer::COMPONENTGROUP_ID , $componentgroupId);
                    $c1->add(ComponentsPeer::QTY2  , 0);
                    $this->compsList = ComponentsPeer::doSelect($c1);
                }
            }
        } 
    }



public function executeCreate()
  {
     $this->getResponse()->setTitle('Create-Tallyin');
    if ($this->getRequest()->isMethod('post'))
    {
        if ($this->getRequestParameter('tally_in[project_id]'))
            return $this->redirect('tallyin/edit?type='.$this->getRequestParameter('tally_in[type]')."&projectid=".$this->getRequestParameter('tally_in[project_id]'));
        else
            return $this->redirect('tallyin/edit?type='.$this->getRequestParameter('tally_in[type]')."&tallyno=".$this->getRequestParameter('tally_in[tallyno]'));
    }
  }
  public function executeEdit()
  {
       $this->getResponse()->setTitle('WMS-Edit-TallyIn');
    $this->tally_in = $this->getTallyInOrCreate();

    //revise MR
    $reviseId = $this->getRequestParameter('prepare_revise_Id');
    if ($reviseId != '' && $reviseId != null)
    {
       $rvObject = TallyInPeer::retrieveByPK($reviseId);
       if (!$rvObject) {
                $this->getRequest()->setError('edit', 'Could not revise this TI because it is not available!');
                $this->forward('tallyin', 'list');
       }
       $this->tally_in = $rvObject->copy();
       $this->tally_in->setReviseId($reviseId);
       $this->tally_in->setStatus(0);
       $componentGroup = new ComponentGroup();
       $componentGroup->setType(1);
       $componentGroup->save();
       $componentGroupId = $rvObject->getComponentgroupId();
       $c= new Criteria();
       $c->add(ComponentsPeer::COMPONENTGROUP_ID , $componentGroupId);
       $compsList = ComponentsPeer::doSelect($c);
       foreach ($compsList  as $comps) {
           $compsNew = $comps->copy();
           $compsNew->setComponentId($comps->getComponentId());
           $compsNew->setComponentgroupId($componentGroup->getId());
           $compsNew->setQty1($comps->getQty1());
           $compsNew->setQty2($comps->getQty2());
           $compsNew->setQty4($comps->getQty4());
           $compsNew->save();
       }
       $this->tally_in->setComponentgroupId($componentGroup->getId());
       $this->tally_in->save();
    }
    
    if ($this->tally_in->getStatus()== CommonValues::$gTLStatus['key']['Published']) {
        $this->getRequest()->setError('edit', 'Cannot edit this TallyIn. It was published.');
        $this->forward('tallyin', 'list');
    }

    if (!($this->getRequestParameter('type')=== null || $this->getRequestParameter('type')=== ''))
    {
        $this->tally_in->setType($this->getRequestParameter('type'));
    }
    if (!($this->getRequestParameter('tallyno') === null || $this->getRequestParameter('tallyno') === ''))
    {
        $this->tally_in->setTallyno($this->getRequestParameter('tallyno'));
    }
    if (!($this->getRequestParameter('projectid') === null || $this->getRequestParameter('projectid') === ''))
    {
        $this->tally_in->setProjectId($this->getRequestParameter('projectid'));
    }

    
    if ($this->getRequest()->isMethod('post'))
    {
      $this->updateTallyInFromRequest();
      if ( $this->tally_in->getType() == CommonValues::$gTallyInType['key']['Production'])
      {
            $this->tally_in->setProjectId($this->tally_in->getTallyno());
      }
      $this->tally_in->setTallyincode(CommonValues::GenerateAutoNumber('TALLYIN', $this->tally_in->getTallyincode(), 'TI', 'm'));
      //Tien code here
      $qtys = $this->getRequestParameter('qtys');
      $rowIds = $this->getRequestParameter('rowIds');
      
      if (isset($rowIds) && count($rowIds) && isset($qtys) && count($qtys) ) {
      	if ($this->tally_in->getComponentgroupId()) {
      	    $c = new Criteria();
      	    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $this->tally_in->getComponentgroupId());
      	    ComponentsPeer::doDelete($c);
      	}
      	$componentGroup = new ComponentGroup();
      	if ($componentGroup)    {
      		$componentGroup->setType(1);
      		$componentGroup->save();
      		$componentGroupId = $componentGroup->getId();
      		
      		if ($componentGroupId) {
      			$this->tally_in->setComponentgroupId($componentGroupId);
      			for($i=0; $i < count($rowIds); $i++){
                            if ($qtys[$i] > 0) {
      				$components = new Components();
      				if ($components){
      					$components->setComponentgroupId($componentGroupId);
      					$components->setComponentId($rowIds[$i]);
      					$components->setQty1($qtys[$i]);
      					$components->save();
      				}
                            }
      			}	      			
      		}
      	}
      }

      //add user id
      $this->tally_in->setUserId($this->getUser()->getGuardUser()->getId());

      try
      {
          if ($this->getRequestParameter('save_as_approved'))
          {
            $this->tally_in->setStatus(1);

            $this->saveTallyIn($this->tally_in);

            if ($this->tally_in->getType() == CommonValues::$gTallyInType['key']['Supplier']) {
                $po = POPeer::retrieveByPK($this->tally_in->getTallyno());
                if (!$po){
                    $this->getRequest()->setError('publish', 'PO of this TallyIn was removed.');
                    $this->forward('tallyin','list');
                }
                $POCompGroupId = $po->getComponentgroupId();

                $c = new Criteria();
                $c->add(ComponentsPeer::COMPONENTGROUP_ID, $this->tally_in->getComponentgroupId());
                $componentsList = ComponentsPeer::doSelect($c);

                foreach ($componentsList as $components) {
                    $componentId = $components->getComponentId();
                    $c = new Criteria();
                    $c->add(WarehousePeer::COMPONENT_ID , $componentId);
                    $warehouse = WarehousePeer::doSelectOne($c);
                    $warehouse->setQtyordered($warehouse->getQtyordered() - $components->getQty1() );
                    $c = new Criteria();
                    $c->add(ComponentsPeer::COMPONENT_ID , $componentId);
                    $c->add(ComponentsPeer::COMPONENTGROUP_ID , $POCompGroupId);
                    $comps = ComponentsPeer::doSelectOne($c);
                    if ($comps)  {
                        $comps->setQty4($comps->getQty4() - $components->getQty1());
                        $comps->save();
                    }
                    $warehouse->save();
                }
            }
          }
        $this->saveTallyIn($this->tally_in);
      }
      catch (PropelException $e)
      {
        $this->getRequest()->setError('edit', 'Could not save the edited Tally ins.');
        return $this->forward('tallyin', 'list');
      }

      $this->getUser()->setFlash('notice', 'Your modifications have been saved');

      if ($this->getRequestParameter('save_as_approved'))
              {
              	return $this->redirect('tallyin/list');
              }
      else if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('tallyin/create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('tallyin/list');
      }
      else
      {
        return $this->redirect('tallyin/edit?id='.$this->tally_in->getId());
      }
    }
    else
    {
      $this->labels = $this->getLabels();
    }
  }
  
  public function executeList()
  {
    $this->getResponse()->setTitle('WMS-TallyIn-List');
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/tally_in/filters');

    // pager
    $this->pager = new sfPropelPager('TallyIn', 25);
    $c = new Criteria();
    $c->addDescendingOrderByColumn(TallyInPeer::TALLYINCODE);
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', $this->getUser()->getAttribute('page', 1, 'sf_admin/tally_in')));
    $this->pager->init();
    // save page
    if ($this->getRequestParameter('page')) {
        $this->getUser()->setAttribute('page', $this->getRequestParameter('page'), 'sf_admin/tally_in');
    }
  }  
  
public function handleErrorEdit()
  {
    $this->preExecute();
    $this->tally_in = $this->getTallyInOrCreate();
    $this->updateTallyInFromRequest();

    $this->labels = $this->getLabels();
    
    //transfer data to edit_form template
    $this->tally_in->qtys = $this->getRequestParameter('qtys');
    $this->tally_in->qty2s = $this->getRequestParameter('qty2s');
    $this->tally_in->rowIds = $this->getRequestParameter('rowIds');

    return sfView::SUCCESS;
  }
  protected function getLabels()
  {
    return array(
      'tally_in{id}' => 'Id:',
      'tally_in{tallyincode}' => 'TallyIn Number:',
      'tally_in{type}' => 'Type:',
      'tally_in{tallyno}' => 'Ref Number:',
      'tally_in{created_at}' => 'TallyIn Date:',
      'tally_in{componentgroup_id}' => 'Component List:',
      'qtys' => 'Component List:',
    );
  }
}
